<?php

namespace Home\Controller;

use Common\Service\ChuanglanSmsTpl;
use Common\Service\Qiniu;
use Common\Service\Sms;
use Common\Service\Validator;

/**
 * 审核员
 * Class AuditController
 * @package Home\Controller
 */
class AuditController extends BaseController
{
    public function __construct()
    {
        //var_dump($key = md5('132546'));die;
        //$filepath = 'C:\Users\Administrator\Desktop\3.jpg';
        //var_dump(Qiniu::upload($filepath,'3.jpg'));die;;
    }

    public function test()
    {
        ChuanglanSmsTpl::sendActivitySmsToStore(1);
    }

    /**
     * 活动添加
     */
    public function add()
    {
        $arr = I('post.');
        $data['name'] = $arr['name'];
        $data['audit_user_id'] = $arr['audit_user_id'];
        $data['activity_start_time'] = $arr['activity_start_time'];
        $data['activity_end_time'] = $arr['activity_end_time'];
        $data['order_end_time'] = $arr['order_end_time'];
        $data['up_start_time'] = $arr['up_start_time'];
        $data['up_end_time'] = $arr['up_end_time'];
        $data['store_ids'] = $arr['store_ids'];
        $data['img_ids'] = $arr['img_ids'];
        $data['add_time'] = time();
        $user = $this->checkUser('audit', $data['audit_user_id']);
        if (!$user) {
            $this->ajaxReturn(['status' => false, 'code' => 1003, 'msg' => '用户信息有误', 'data' => []]);
        }

        if (!$data['name'] || !$data['activity_start_time'] || !$data['activity_end_time'] || !$data['up_end_time'] ||
            !$data['up_start_time'] || !$data['store_ids'] || !$data['img_ids'] || !$data['order_end_time']
        ) {
            $this->ajaxReturn(['status' => false, 'code' => 1002, 'msg' => '请填写完整数据再添加', 'data' => []]);
        }
        $ret = M('activity')->add($data);
        if ($ret) {
            //初始化订单
            $model = A('order');
            $model->InitOrder($ret);
            //活动创建成功，给店长发送短信
            ChuanglanSmsTpl::sendActivitySmsToStore($ret);
            $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '添加活动成功', 'data' => []]);
        } else {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '服务器异常', 'data' => []]);
        }
    }

    /**
     * 上传效果图
     */
    public function upImg()
    {
        $arr = I('post.');
        $data['image_name'] = $arr['image_name'];
        $data['image_url'] = $arr['image_url'];
        $data['store_ids'] = $arr['store_ids'];
        $data['add_time'] = time();

        if (!$data['image_name'] || !$data['image_url'] || !$data['store_ids']) {
            $this->ajaxReturn(['status' => false, 'code' => 1002, 'msg' => '请填写完整数据再添加', 'data' => []]);
        }
        $ret = M('activity_image')->add($data);
        if ($ret) {
            $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '上传效果图成功', 'data' => ['id' => $ret]]);
        } else {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '服务器异常', 'data' => []]);
        }
    }

    /**
     * 上传所需要的token，domain
     */
    public function uploadInfo()
    {
        $num = I('num');
        $data = Qiniu::getUpimageInfo($num);
        $ret = [
            'status' => true,
            'code' => 1000,
            'msg' => '',
            'data' => $data
        ];

        $this->ajaxReturn($ret);
    }

    /**
     * 获取门店信息
     */
    public function getStoreInfo()
    {
        $id = I('id');
        $size = I('size', 100);
        $page = I('page', 1);
        $keyword = I('keyword');

        $user = $this->checkUser('audit', $id);
        if (!$user) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '用户信息有误', 'data' => []]);
        }

        //这里没有加入审核员的id，直接返回所有
        $where = [];
        if ($keyword) {
            $where['store_name'] = ['like', '%' . $keyword . '%'];
        }

        $where['audit_user_id'] = $user['id'];

        $data = $this->getList('store', $where, $size, $page);

        if ($page == 1 && !$data) {
            $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '当前无门店信息', 'data' => []]);
        }

        if ($page > 1 && !$data) {
            $this->ajaxReturn(['status' => false, 'code' => 1003, 'msg' => '无更多数据', 'data' => []]);
        }

        $ret = [
            'status' => true,
            'code' => 1000,
            'msg' => '查询门店成功',
            'data' => $data
        ];

        $this->ajaxReturn($ret);
    }

    /**
     * 获取活动列表
     * @return mixed
     */
    public function activityList()
    {
        $uid = I('id');
        $size = I('size', 5);
        $page = I('page', 1);
        $keyword = I('keyword');
        $type = I('type');  //1=>当前活动。2=>历史活动

        $user = $this->checkUser('audit', $uid);
        if (!$user) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '用户信息有误', 'data' => []]);
        }

        if ($keyword) {
            $where['name'] = ['like', '%' . $keyword . '%'];
        }

        if ($type == 1) {
            $where['activity_end_time'] = ['gt', time()];
        }

        if ($type == 2) {
            $where['activity_end_time'] = ['lt', time()];
        }

        $where['audit_user_id'] = $uid;
        $where['status'] = 1;
        $data = $this->getList('activity', $where, $size, $page);

        if ($page == 1 && !$data) {
            $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '当前无活动数据', 'data' => []]);
        }

        if ($page > 1 && !$data) {
            $this->ajaxReturn(['status' => false, 'code' => 1003, 'msg' => '无更多数据', 'data' => []]);
        }

        foreach ($data as $k => $v) {
            //待审核订单数量
            $order_num = M('order')->where(['activity_id' => $v['id'], 'order_status' => 1])->count();
            $data[$k]['store_num'] = count(explode(',', $v['store_ids']));
            $data[$k]['store_placed_num'] = 0;
            $data[$k]['status'] = 0;
            $data[$k]['order_num'] = $order_num;
        }

        $ret = [
            'status' => true,
            'code' => 1000,
            'msg' => '获取活动列表',
            'data' => $data
        ];
        $this->ajaxReturn($ret);
    }

    /**
     * 审核员删除订单，待确定
     */
    public function delActivity()
    {
        $activity_id = I('activity_id');
        //未下单的订单为0状态，可以删除
        $order_num = M('order')->where(['activity_id' => $activity_id, 'order_status' => 0])->count();
        if ($order_num > 0) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '活动存在正在进行的订单，不能进行删除', 'data' => []]);
        }

        $data['status'] = 0;
        $res = M('activity')->where(['id' => $activity_id])->save($data);
        if ($res !== false) {
            $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '删除成功', 'data' => []]);
        } else {
            $this->ajaxReturn(['status' => false, 'code' => 1002, 'msg' => '服务器异常', 'data' => []]);
        }
    }

    /**
     * 活动订单列表
     */
    public function activityOrderList()
    {
        $activity_id = I('activity_id');
        $size = I('size', 5);
        $page = I('page', 1);
        $status = I('status');

        $field = 'o.order_status,s.store_name,o.order_no,s.address';
        $where['activity_id'] = $activity_id;
        if(!$activity_id)
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '参数有误', 'data' => '']);

        if($status)
            $where['status'] = $status;

        $count = M('order')
            ->alias('o')
            ->join('left join wk_store s ON o.store_id = s.id')
            ->where($where)
            ->field($field)
            ->count();

        $orderList = M('order')
            ->alias('o')
            ->join('left join wk_store s ON o.store_id = s.id')
            ->where($where)
            ->field($field)
            ->page("$page,$size")
            ->select();

        foreach ($orderList as $k => $v) {
            $orderList[$k]['order_status_msg'] = $this->statusMsg()[$v['order_status']];
            $orderList[$k]['material_num'] = 0;
            $orderList[$k]['store_address'] = $v['address'];
            $orderList[$k]['order_status'] = $v['order_status'];
        }

        $info = M('order')->where(['activity_id' => $activity_id])->select();
        $tmp['info'] = [
            ['name' => '待审核', 'status' => 1, 'num' => 0],
            ['name' => '审核通过', 'status' => 3, 'num' => 0],
            ['name' => '物料情况', 'status' => 4, 'num' => 0],
            ['name' => '上画待验收', 'status' => 5, 'num' => 0],
            ['name' => '下画待验收', 'status' => 6, 'num' => 0],
            ['name' => '订单完成', 'status' => 7, 'num' => 0]
        ];

        foreach ($info as $kk => $vv) {
            if ($vv['order_status'] == 1) {//待审核
                $tmp['info'][0]['num']++;
            }

            if ($vv['order_status'] == 3) {//审核通过
                $tmp['info'][1]['num']++;
            }
        }

        $tmp['list'] = $orderList;
        $tmp['order_count'] = $count;
        $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '活动订单列表', 'data' => $tmp]);
    }

    /**
     * 活动订单详情
     */
    public function activityOrderDetail()
    {
        $order_no = I('order_no');
        $where['order_no'] = $order_no;
        $field = 'o.order_status,s.store_name,s.mobile,s.address,o.is_down,o.up_time,o.down_time';
        $order = M('order')
            ->alias('o')
            ->join('left join wk_store s ON o.store_id = s.id')
            ->where($where)
            ->field($field)
            ->find();

        if (!$order) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '订单号有误', 'data' => []]);
        }
        $order['order_status_msg'] = $this->statusMsg()[$order['order_status']];
        $order['is_down_msg'] = $order['is_down'] == 0 ? '否' : '是';
        $order['up_time'] = date('Y-m-d', $order['up_time']);
        if ($order['is_down'] == 0) {
            $order['down_time'] = 0;
        } else {
            $order['down_time'] = date('Y-m-d', $order['down_time']);
        }

        $order_ads = $this->orderAds($order_no);
        $order['order_ads'] = $order_ads;
        $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '活动订单详情', 'data' => $order]);
    }

    /**
     * 订单广告图
     * @param $order_no
     * @return mixed
     */
    public function orderAds($order_no)
    {
        $field = 'ads_id,ads_name,ads_type,width,height,materiel_id,activity_image_id,num';
        $order_ads = M('order_ads')->where(['order_no' => $order_no])->field($field)->select();
        foreach ($order_ads as $k => $v) {
            if ($v['ads_type'] == 1) {
                $adids = M('ads_detail')->where(['ads_id' => $v['ads_id']])->field('id')->select();
                foreach ($adids as $v1) {
                    $ids[] = $v1['id'];
                }
                $field1 = 'width,height,materiel_name,ads_name as ads_block_name,activity_image_url';
                $where['ads_detail_id'] = ['in', $ids];
                $where['order_no'] = $order_no;
                $order_ads_detail = M('order_ads_detail')->where($where)->field($field1)->select();
            } else {
                $materiel = M('materiel')->where(['id' => $v['materiel_id']])->field('name')->find();
                $activity_image = M('activity_image')->where(['id' => $v['activity_image_id']])->field('image_url')->find();
                $order_ads_detail = [
                    'width' => $v['width'],
                    'height' => $v['height'],
                    'materiel_name' => $materiel['name'],
                    'activity_image_url' => $activity_image['image_url'],
                    'ads_block_name' => $v['ads_name'],
                ];
            }

            unset($order_ads[$k]['ads_id']);
            unset($order_ads[$k]['materiel_id']);
            unset($order_ads[$k]['width']);
            unset($order_ads[$k]['height']);
            unset($order_ads[$k]['activity_image_id']);
            $order_ads[$k]['detail'] = $order_ads_detail;
        }
        return $order_ads;
    }

    /**
     * 审核员审核订单
     */
    public function auditOrder()
    {
        $order_no = I('order_no');
        $user_id = I('user_id');
        $reason = I('reason', '');
        $status = I('status');//2审核未通过，3审核通过

        if (!in_array($status, [2, 3])) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '状态有误', 'data' => []]);
        }

        if ($status == 2 && !$reason) {
            $this->ajaxReturn(['status' => false, 'code' => 1002, 'msg' => '未通过必须填写原因', 'data' => []]);
        }

        $user = $this->checkUser('audit', $user_id);
        if (!$user) {
            $this->ajaxReturn(['status' => false, 'code' => 1003, 'msg' => '用户信息有误', 'data' => []]);
        }

        //判断订单是否提交审核过
        if ($this->checkOrderAudit($order_no, $user_id)) {
            $this->ajaxReturn(['status' => false, 'code' => 1006, 'msg' => '该订单已经审核过', 'data' => []]);
        }

        $order = M('order')->where(['order_no' => $order_no])->find();
        if (!$order) {
            $this->ajaxReturn(['status' => false, 'code' => 1004, 'msg' => '订单号有误', 'data' => []]);
        }

        //如果是审核通过，但是存在高空物料
        //11=>已审核待高空报价 12=>高空报价完成待审核 13=>高空报价审核失败 14=>高空报价审核成功(回到3状态)
        if ($status == 3) {
            $r = M('order_ads')->where(['order_no' => $order_no, 'is_upper_air' => 1])->find();
            if ($r) {
                $status = 11;
            }
        }

        $data = [
            'audit_user_id' => $user_id,
            'order_status' => $status,
            'audit_result' => $reason,
            'update_time' => time()
        ];

        $res = M('order')->where(['order_no' => $order_no])->save($data);
        if ($res !== false) {
            $user['user_id'] = $user['id'];
            $user['user_name'] = $user['name'];
            $res1 = orderLog($order_no, $status, $user, '审核员审核订单', 'add');
            if (!$res1) {
                $this->ajaxReturn(['status' => false, 'code' => 1006, 'msg' => '审核订单日志记录失败', 'data' => []]);
            }

            $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '审核订单成功', 'data' => []]);
        } else {
            $this->ajaxReturn(['status' => false, 'code' => 1005, 'msg' => '服务器异常', 'data' => []]);
        }
    }

    /**
     * 审核员高空报价审核
     */
    public function auditUpperOrder()
    {
        $order_no = I('order_no');
        $user_id = I('user_id');
        $reason = I('reason', '');
        $status = I('status');//2审核未通过，3审核通过

        if (!in_array($status, [2, 3])) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '状态有误', 'data' => []]);
        }

        if ($status == 2 && !$reason) {
            $this->ajaxReturn(['status' => false, 'code' => 1002, 'msg' => '未通过必须填写原因', 'data' => []]);
        }

        $user = $this->checkUser('audit', $user_id);
        if (!$user) {
            $this->ajaxReturn(['status' => false, 'code' => 1003, 'msg' => '用户信息有误', 'data' => []]);
        }

        // //判断订单是否提交审核过
        // if ($this->checkOrderAudit($order_no, $user_id)) {
        //     $this->ajaxReturn(['status' => false, 'code' => 1006, 'msg' => '该订单已经审核过', 'data' => []]);
        // }

        $order = M('order')->where(['order_no' => $order_no])->find();
        if (!$order) {
            $this->ajaxReturn(['status' => false, 'code' => 1004, 'msg' => '订单号有误', 'data' => []]);
        }

        if ($order['order_status'] != 11 && $order['order_status'] != 12) {
            $this->ajaxReturn(['status' => false, 'code' => 1005, 'msg' => '请按照正常流程操作', 'data' => []]);
        }


        //如果审核不过
        if ($status == 2) {
            $status = 13;
        }

        $data = [
            'audit_user_id' => $user_id,
            'order_status' => $status,
            'audit_result' => $reason,
            'update_time' => time()
        ];

        $res = M('order')->where(['order_no' => $order_no])->save($data);
        if ($res !== false) {
            $user['user_id'] = $user['id'];
            $user['user_name'] = $user['name'];
            $res1 = orderLog($order_no, $status, $user, '审核员高空报价审核通过', 'add');
            if (!$res1) {
                $this->ajaxReturn(['status' => false, 'code' => 1006, 'msg' => '审核订单日志记录失败', 'data' => []]);
            }

            $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '审核订单成功', 'data' => []]);
        } else {
            $this->ajaxReturn(['status' => false, 'code' => 1005, 'msg' => '服务器异常', 'data' => []]);
        }
    }

    /**
     * 发送验证码
     */
    public function sendCode()
    {
        $phone = I('phone');
        if (!Validator::checkPhone($phone)) {
            $this->ajaxReturn(['status' => false, 'code' => 1002, 'msg' => '请填写正确的手机号', 'data' => []]);
        }

        $res = ChuanglanSmsTpl::sendCode($phone, 'yzm');
        if ($res) {
            $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '发送验证码成功', 'data' => []]);
        } else {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '发送验证码失败', 'data' => []]);
        }
    }

    /**
     * 修改手机号
     */
    public function updPhone()
    {
        $ori_phone = I('ori_phone');
        $new_phone = I('new_phone');
        $code = I('code');

        if (!Validator::checkPhone($ori_phone)) {
            $this->ajaxReturn(['status' => false, 'code' => 1002, 'msg' => '请填写正确的原始手机号', 'data' => []]);
        }
        if (!Validator::checkPhone($new_phone)) {
            $this->ajaxReturn(['status' => false, 'code' => 1003, 'msg' => '请填写正确的新手机号', 'data' => []]);
        }

        $info = M('audit')->where(['mobile' => $ori_phone])->find();
        if (!$info) {
            $this->ajaxReturn(['status' => false, 'code' => 1004, 'msg' => '该手机号尚未注册', 'data' => []]);
        }

        $scode = S($new_phone);
        if ($code && $code == $scode) {
            $rs = M('audit')->where(['mobile' => $ori_phone])->save(['mobile' => $new_phone, 'update_time' => time()]);
            if ($rs !== false) {
                $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '修改手机号成功', 'data' => []]);
            } else {
                $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '服务器异常', 'data' => []]);
            }
        } else {
            $this->ajaxReturn(['status' => false, 'code' => 1005, 'msg' => '验证码有误', 'data' => []]);
        }
    }

    /**
     * 修改密码
     */
    public function updPassword()
    {
        $ori_pwd = I('ori_pwd');
        $new_pwd = I('new_pwd');
        $conf_pwd = I('conf_pwd');
        $uid = I('id');

        if ($new_pwd != $conf_pwd) {
            $this->ajaxReturn(['status' => false, 'code' => 1002, 'msg' => '两次密码不一致', 'data' => []]);
        }

        if ($new_pwd == $ori_pwd) {
            $this->ajaxReturn(['status' => false, 'code' => 1005, 'msg' => '新密码不能跟原密码相同', 'data' => []]);
        }

        $user = $this->checkUser('audit', $uid);
        if ($user) {
            if ($ori_pwd == $user['password']) {
                $rs = M('audit')->where(['id' => $uid])->save(['password' => $new_pwd, 'update_time' => time()]);
                if ($rs !== false) {
                    $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '修改密码成功', 'data' => []]);
                } else {
                    $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '服务器异常', 'data' => []]);
                }
            } else {
                $this->ajaxReturn(['status' => false, 'code' => 1003, 'msg' => '原始密码错误', 'data' => []]);
            }
        } else {
            $this->ajaxReturn(['status' => false, 'code' => 1004, 'msg' => '用户信息错误', 'data' => []]);
        }
    }
}